package com.start.workflow.core.dispatcher;

import com.start.common.std.StartBaseSingleton;
import com.start.common.tools.SpringContextTools;
import com.start.common.tools.StartMapTools;
import com.start.workflow.core.event.StartWorkFLowEvent;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public abstract class StartBaseWorkFlowEvent<T extends StartWorkFLowEvent> extends StartBaseSingleton<StartBaseWorkFlowEvent> {

    protected List<T> globalEvent;
    private Map<String, List<T>> categoryMap;
    private Map<String, List<T>> keyMap;



    /**
     * 调用初始化函数
     */
    @Override
    public final void init() {

    }



    /**
     * 添加事件
     *
     * @param event
     */
    public void addEvent(T event) {
        if (event == null) {
            throw new RuntimeException("event is null");
        }
        if (StringUtils.isNotEmpty(event.key())) {
            StartMapTools.mapAddValue(keyMap, event, event.key(), event.SPLIT());
            return;
        }
        if (StringUtils.isNotEmpty(event.categoryKey())) {
            StartMapTools.mapAddValue(categoryMap, event, event.key(), event.SPLIT());
            return;
        }
        globalEvent.add(event);
    }


    public Map<String, List<T>> getCategoryMap() {
        return categoryMap;
    }

    public Map<String, List<T>> getKeyMap() {
        return keyMap;
    }

    public List<T> getGlobalEvents() {
        return globalEvent;
    }

    public List<T> getEventByKey(String key) {
        if (keyMap == null) return new ArrayList<>();
        if (StringUtils.isEmpty(key)) return new ArrayList<>();
        return keyMap.getOrDefault(key, new ArrayList<>());
    }

    public List<T> getEventByCategory(String category) {
        if (categoryMap == null) return new ArrayList<>();
        if (StringUtils.isEmpty(category)) return new ArrayList<>();
        return categoryMap.getOrDefault(category, new ArrayList<>());
    }

    /**
     * 获取事件类型class
     *
     * @return
     */
    protected abstract Class<T> getEventClazz();
}
